#include "stdafx.h"
#include "MysqlTypeUtil.h"
#include "stdlib.h"
#include <utility/Time.h>
#include <boost/lexical_cast.hpp>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace serika
{
	using ut::Time;

	namespace db
	{
		MysqlTypeUtil::MysqlTypeUtil()
		{
		}
	
		MysqlTypeUtil::~MysqlTypeUtil()
		{
		}
	
		void MysqlTypeUtil::InsertValue(FieldMap* fm, MYSQL_FIELD* field, const char* value, unsigned long length)
		{
			if (value == 0)
			{
				fm->insert(std::make_pair(field->name, NIL));
				return;
			}
	
			switch (field->type)
			{
			case MYSQL_TYPE_SHORT:
			case MYSQL_TYPE_LONG:
			case MYSQL_TYPE_INT24:
			case MYSQL_TYPE_TINY:
				fm->insert(std::make_pair(field->name, Any(boost::lexical_cast<int>(value))));
				break;
	
			case MYSQL_TYPE_LONGLONG:
	// #ifdef _WIN32
	// 			fm->insert(std::make_pair(field->name, Any(static_cast<long long>(_atoi64(value)))));
	// #else
	//			fm->insert(std::make_pair(field->name, Any(atoll(value))));
	// #endif
				fm->insert(std::make_pair(field->name, Any(boost::lexical_cast<long long>(value))));
				break;
	
			case MYSQL_TYPE_DECIMAL:
			case MYSQL_TYPE_FLOAT:
			case MYSQL_TYPE_DOUBLE:
			case MYSQL_TYPE_NEWDECIMAL:
				fm->insert(std::make_pair(field->name, Any(boost::lexical_cast<double>(value))));
				break;
	
			case MYSQL_TYPE_TIMESTAMP:
			case MYSQL_TYPE_DATETIME:
				{
					Time t = Time::FromString(ut::StringHelper::Convert(value).c_str());
					fm->insert(std::make_pair(field->name, Any(t)));
				}
				break;
	
			case MYSQL_TYPE_YEAR:
				{
					Time t;
					t.SetYear(boost::lexical_cast<int>(value));
					fm->insert(std::make_pair(field->name, Any(t)));
				}
	
			case MYSQL_TYPE_DATE:
			case MYSQL_TYPE_NEWDATE:
				{
					Time t = Time::FromDateString(ut::StringHelper::Convert(value).c_str());
					fm->insert(std::make_pair(field->name, Any(t)));
				}
				break;
	
			case MYSQL_TYPE_TIME:
				{
					Time t = Time::FromTimeString(ut::StringHelper::Convert(value).c_str());
					fm->insert(std::make_pair(field->name, Any(t)));
				}
				break;
	
			case MYSQL_TYPE_VARCHAR:
			case MYSQL_TYPE_ENUM:
			case MYSQL_TYPE_SET:
			case MYSQL_TYPE_TINY_BLOB:
			case MYSQL_TYPE_MEDIUM_BLOB:
			case MYSQL_TYPE_LONG_BLOB:
			case MYSQL_TYPE_BLOB:
			case MYSQL_TYPE_VAR_STRING:
			case MYSQL_TYPE_STRING:
				{
					std::string s(value, length);
					fm->insert(std::make_pair(field->name, Any(ut::StringHelper::Convert(s))));
				}
				break;
	
			default:
				fm->insert(std::make_pair(field->name, Any(std::string(value))));
				break;
			}
		}
	}
}
